'use client';

import { useState, useEffect, useCallback } from 'react';
import { useParams, useRouter, useSearchParams } from 'next/navigation';
import { Button } from "@heroui/button";

import { Chip } from "@heroui/chip";
import { Image } from "@heroui/image";

// 模拟漫画页面数据
const getMangaPages = (mangaId: string, chapterId: number) => {
    // 模拟每章有10-15页
    const pageCount = Math.floor(Math.random() * 6) + 10;
    return Array.from({length: pageCount}, (_, i) => ({
        id: i + 1,
        url: `https://heroui.com/images/card-example-${(i % 6) + 1}.jpeg`,
        width: 800,
        height: 1200
    }));
};

// 模拟漫画基本信息
const getMangaInfo = (id: string) => {
    return {
        id,
        title: "进击的巨人",
        totalChapters: 139
    };
};

// 为静态导出生成参数
export async function generateStaticParams() {
    // 生成1-20的漫画ID
    return Array.from({length: 20}, (_, i) => ({
        id: (i + 1).toString()
    }));
}

export default function Read() {
    const params = useParams();
    const router = useRouter();
    const searchParams = useSearchParams();

    const mangaId = params.id as string;
    const currentChapter = parseInt(searchParams.get('chapter') || '1');

    const [currentPage, setCurrentPage] = useState(1);
    const [isFullscreen, setIsFullscreen] = useState(false);
    const [readingMode, setReadingMode] = useState<'single' | 'double'>('single');
    const [showControls, setShowControls] = useState(true);

    const manga = getMangaInfo(mangaId);
    const pages = getMangaPages(mangaId, currentChapter);

    // 键盘导航
    const handleKeyPress = useCallback((event: KeyboardEvent) => {
        switch (event.key) {
            case 'ArrowLeft':
            case 'a':
            case 'A':
                if (currentPage > 1) {
                    setCurrentPage(prev => prev - 1);
                }
                break;
            case 'ArrowRight':
            case 'd':
            case 'D':
            case ' ':
                if (currentPage < pages.length) {
                    setCurrentPage(prev => prev + 1);
                }
                break;
            case 'f':
            case 'F':
                setIsFullscreen(prev => !prev);
                break;
            case 'Escape':
                if (isFullscreen) {
                    setIsFullscreen(false);
                }
                break;
        }
    }, [currentPage, pages.length, isFullscreen]);

    useEffect(() => {
        document.addEventListener('keydown', handleKeyPress);
        return () => document.removeEventListener('keydown', handleKeyPress);
    }, [handleKeyPress]);

    // 控制栏自动隐藏
    useEffect(() => {
        if (isFullscreen) {
            const timer = setTimeout(() => {
                setShowControls(false);
            }, 3000);
            return () => clearTimeout(timer);
        } else {
            setShowControls(true);
        }
    }, [isFullscreen, currentPage]);

    const handlePrevPage = () => {
        if (currentPage > 1) {
            setCurrentPage(prev => prev - 1);
        } else if (currentChapter > 1) {
            // 跳转到上一章的最后一页
            router.push(`/content/mangas/${mangaId}/read?chapter=${currentChapter - 1}`);
        }
    };

    const handleNextPage = () => {
        if (currentPage < pages.length) {
            setCurrentPage(prev => prev + 1);
        } else if (currentChapter < manga.totalChapters) {
            // 跳转到下一章的第一页
            router.push(`/content/mangas/${mangaId}/read?chapter=${currentChapter + 1}`);
        }
    };

    const handleChapterChange = (newChapter: number) => {
        router.push(`/content/mangas/${mangaId}/read?chapter=${newChapter}`);
    };

    const toggleFullscreen = () => {
        setIsFullscreen(prev => !prev);
        setShowControls(true);
    };

    return (
        <div className={`${isFullscreen ? 'fixed inset-0 z-50 bg-black' : 'min-h-screen bg-gray-50 dark:bg-gray-900'}`}>
            {/* 顶部控制栏 */}
            <div className={`${
                isFullscreen
                    ? `fixed top-0 left-0 right-0 z-10 transition-transform duration-300 ${
                        showControls ? 'translate-y-0' : '-translate-y-full'
                    }`
                    : 'sticky top-0 z-10'
            } bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 py-3`}>
                <div className="flex items-center justify-between max-w-7xl mx-auto">
                    <div className="flex items-center gap-4">
                        <Button
                            variant="light"
                            size="sm"
                            onPress={() => router.push(`/content/mangas/${mangaId}`)}
                            startContent={
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                                </svg>
                            }
                        >
                            返回详情
                        </Button>

                        <div className="text-sm text-gray-600 dark:text-gray-400">
                            <span className="font-medium text-gray-900 dark:text-white">{manga.title}</span>
                            <span className="mx-2">·</span>
                            <span>第{currentChapter}话</span>
                            <span className="mx-2">·</span>
                            <span>{currentPage}/{pages.length}</span>
                        </div>
                    </div>

                    <div className="flex items-center gap-2">
                        {/* 章节导航 */}
                        <Button
                            variant="light"
                            size="sm"
                            isDisabled={currentChapter <= 1}
                            onPress={() => handleChapterChange(currentChapter - 1)}
                        >
                            上一章
                        </Button>

                        <Chip variant="flat" size="sm">
                            {currentChapter}/{manga.totalChapters}
                        </Chip>

                        <Button
                            variant="light"
                            size="sm"
                            isDisabled={currentChapter >= manga.totalChapters}
                            onPress={() => handleChapterChange(currentChapter + 1)}
                        >
                            下一章
                        </Button>

                        {/* 阅读设置 */}
                        <Button
                            variant="light"
                            size="sm"
                            onPress={() => setReadingMode(prev => prev === 'single' ? 'double' : 'single')}
                        >
                            {readingMode === 'single' ? '单页' : '双页'}
                        </Button>

                        <Button
                            variant="light"
                            size="sm"
                            onPress={toggleFullscreen}
                        >
                            {isFullscreen ? '退出全屏' : '全屏'}
                        </Button>
                    </div>
                </div>
            </div>

            {/* 主要阅读区域 */}
            <div className={`${isFullscreen ? 'pt-16' : 'pt-4'} pb-4 flex-1`}>
                <div className="max-w-4xl mx-auto px-4">
                    {readingMode === 'single' ? (
                        /* 单页模式 */
                        <div className="flex justify-center">
                            <div className="relative group">
                                <Image
                                    alt={`第${currentChapter}话 - 第${currentPage}页`}
                                    src={pages[currentPage - 1]?.url}
                                    className="max-w-full h-auto shadow-lg rounded-lg"
                                    removeWrapper
                                />

                                {/* 页面导航热区 */}
                                <div className="absolute inset-0 flex">
                                    <div
                                        className="w-1/2 h-full cursor-pointer flex items-center justify-start pl-4 opacity-0 hover:opacity-100 transition-opacity"
                                        onClick={handlePrevPage}
                                    >
                                        {currentPage > 1 && (
                                            <div className="bg-black/50 text-white p-2 rounded-full">
                                                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                                                </svg>
                                            </div>
                                        )}
                                    </div>
                                    <div
                                        className="w-1/2 h-full cursor-pointer flex items-center justify-end pr-4 opacity-0 hover:opacity-100 transition-opacity"
                                        onClick={handleNextPage}
                                    >
                                        {currentPage < pages.length && (
                                            <div className="bg-black/50 text-white p-2 rounded-full">
                                                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                                </svg>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                        </div>
                    ) : (
                        /* 双页模式 */
                        <div className="flex justify-center gap-4">
                            {/* 左页 */}
                            {currentPage > 1 && (
                                <div className="relative group">
                                    <Image
                                        alt={`第${currentChapter}话 - 第${currentPage - 1}页`}
                                        src={pages[currentPage - 2]?.url}
                                        className="max-w-full h-auto shadow-lg rounded-lg"
                                        removeWrapper
                                    />
                                </div>
                            )}

                            {/* 右页 */}
                            <div className="relative group">
                                <Image
                                    alt={`第${currentChapter}话 - 第${currentPage}页`}
                                    src={pages[currentPage - 1]?.url}
                                    className="max-w-full h-auto shadow-lg rounded-lg"
                                    removeWrapper
                                />
                            </div>
                        </div>
                    )}
                </div>
            </div>

            {/* 底部控制栏 */}
            <div className={`${
                isFullscreen
                    ? `fixed bottom-0 left-0 right-0 z-10 transition-transform duration-300 ${
                        showControls ? 'translate-y-0' : 'translate-y-full'
                    }`
                    : 'sticky bottom-0 z-10'
            } bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 px-4 py-3`}>
                <div className="flex items-center justify-between max-w-7xl mx-auto">
                    <div className="flex items-center gap-2">
                        <Button
                            variant="light"
                            size="sm"
                            isDisabled={currentPage <= 1 && currentChapter <= 1}
                            onPress={handlePrevPage}
                            startContent={
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                                </svg>
                            }
                        >
                            上一页
                        </Button>

                        <span className="text-sm text-gray-600 dark:text-gray-400 px-3">
                            {currentPage} / {pages.length}
                        </span>

                        <Button
                            variant="light"
                            size="sm"
                            isDisabled={currentPage >= pages.length && currentChapter >= manga.totalChapters}
                            onPress={handleNextPage}
                            endContent={
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                </svg>
                            }
                        >
                            下一页
                        </Button>
                    </div>

                    <div className="text-xs text-gray-500 dark:text-gray-400">
                        使用方向键或 A/D 键翻页，F 键切换全屏
                    </div>
                </div>
            </div>

            {/* 全屏时的鼠标移动检测 */}
            {isFullscreen && (
                <div
                    className="fixed inset-0 z-0"
                    onMouseMove={() => setShowControls(true)}
                    onClick={() => setShowControls(prev => !prev)}
                />
            )}
        </div>
    );
}